package redisson.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties.Pool;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

	@Autowired
	RedisProperties redisProperties;

	@Bean
	RedissonClient redisson() {
		// @formatter:off

		Config config = new Config();
		/* 1. 拼装 address */
		String address = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();

		/* 2. 基础配置 */
		config.useSingleServer()
			  .setAddress(address)
			  .setDatabase(redisProperties.getDatabase())
			  .setPassword(redisProperties.getPassword())
			  .setTimeout((int) redisProperties.getTimeout().toMillis())
			  .setPingConnectionInterval(5);
		/* 3. 连接池可复用 Lettuce 的配置 */
		Pool pool = redisProperties.getLettuce().getPool();
		if (pool != null) {
			config.useSingleServer().setConnectionPoolSize(pool.getMaxActive())
					.setConnectionMinimumIdleSize(pool.getMinIdle());
		}
		// @formatter:on
		return Redisson.create(config);
	}
}
